package com.fejal.seguranca.dao;

import java.util.List;



import com.fejal.dao.HibernateDAO;
import com.fejal.seguranca.dao.HibernateDAOFactory;
import com.fejal.seguranca.bean.Area;


public class AreaDAOHibernate implements AreaDAO {
	
	
	HibernateDAOFactory hibernateDAOFactory = null;
	HibernateDAO<Area> hibernateDAO = null;

	public AreaDAOHibernate() {
		hibernateDAOFactory = new HibernateDAOFactory();
		hibernateDAO = hibernateDAOFactory.getAreaDAO();
	}
	
	
	@Override
	public boolean inserir(Area area) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.add(area);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 
		return ok;
	}

	@Override
	public boolean alterar(Area area) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.update(area);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}

		return ok;
	}

	@Override
	public boolean excluir(Area area) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.remove(area);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 

		return ok;
	}

	@Override
	public Area getArea(int codigoArea) {
		return hibernateDAO.get(codigoArea);
		
	}

	@Override
	public List<Area> getListarTodos() {
		return hibernateDAO.listAll();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Area> getSelecionar(String descricao, String URL) {
		String 	sql = "FROM Area WHERE codigoArea <> 0";

		if (!(descricao.isEmpty())) {
			sql += " AND descricao like '" + descricao + "%' ";  
		}
		
		if (!(URL.isEmpty())) {
			sql += " AND URL like '" + URL + "%' ";  
		}
		
		sql += " ORDER BY descricao";		
 
		List<Area> lista = hibernateDAO.getSession().createQuery(sql).list();
		
		return lista;
	}
	

	@Override
	public boolean isExclusaoLiberada(Area area) {
		// TODO Auto-generated method stub
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean isExiste(Area area) {
		// SQL para verificar se a Area existe
		String 	sql = 	" FROM Area " +
				"WHERE descricao	= '"+ area.getDescricao() + "' AND " +
				"		codigoArea != '" + area.getCodigoArea() + "'";

		List<Area> lista = hibernateDAO.getSession().createQuery(sql).list();
	    
		if (lista.size()<1) {
			return false;
		} else {
			return true;
		}
	}
	
	

}
